package com.example.sherlockzhong.plush_v2.Subscriptions;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sherlockzhong.plush_v2.CardBeans.ConsumptionBean;
import com.example.sherlockzhong.plush_v2.CardIni.ConsumeTableIni;
import com.example.sherlockzhong.plush_v2.Components.buttons.BackButton;
import com.example.sherlockzhong.plush_v2.Constant;
import com.example.sherlockzhong.plush_v2.Models.EcardModel;
import com.example.sherlockzhong.plush_v2.R;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;

/*
 * Created by DosonLeung on 2014/8/28.
 */
public class ConsumptionActivity extends Activity {

    RelativeLayout consume_login_frame;
    TextView consume_msg;
    EditText consume_password;
    Button consume_button;
    JSONArray consumeArray;
    Thread getData = new Thread() {
        @Override
        public void run() {
            consumeArray = EcardModel.getData("");
            handler.sendEmptyMessage(0x123);
        }
    };
    private Activity self = this;
    private ProgressDialog pd;
    private ConsumptionBean CB = new ConsumptionBean();
    Handler handler = new Handler() {
        /**
         * 0x0200 登陸成功
         * 0x0401 密碼錯誤或者網絡超時
         * 0x123  數據加載完畢或加載失敗
         * */
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x0200) {
                stopReflashDialog();
                consume_msg.setText("登陆成功!加载数据");
                getData.start();
                showReflashDialog("加载中...");
            } else if (msg.what == 0x0401) {
                stopReflashDialog();
                try {
                    String msgs = Constant.failedJsonObject.getString("msg");
                    if (msgs.equals("login_failed")) {
                        consume_msg.setText("密码错误");
                    } else {
                        consume_msg.setText("网络超时");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (msg.what == 0x123) {
                stopReflashDialog();
                consume_msg.setText("加载完毕！");
                hideLoginFrame(consume_login_frame);
                if (consumeArray != null) {
                    ConsumeTableIni.initConsumptionTable(consumeArray, CB);
                    ConsumeTableIni.generateConsumeList(ConsumptionActivity.this, (ListView) findViewById(R.id.consmuefull_list), CB.generateConsumeListData(), CB.getSum());
                } else {
                    Toast.makeText(ConsumptionActivity.this, "你今天没有消费哦！", Toast.LENGTH_SHORT).show();
                    ConsumeTableIni.generateConsumeList(ConsumptionActivity.this, (ListView) findViewById(R.id.consmuefull_list), CB.generateConsumeListData(), CB.getSum());
                }
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.consumefull_list);
        ((BackButton) findViewById(R.id.consume_back)).setApp(this);
        initWidget();
        if (EcardModel.isVerify()) {
            getData.start();
            this.showReflashDialog("加载中...");
        } else {
            showLoginFrame(consume_login_frame);
        }
        /*
        consumetablebean.setHeaders(new String[]{"-17￥","-7￥","-3.5￥","+100￥"});
        consumetablebean.setContents(new String[]{"芷园三楼","西园超市","绿榕园","中国建设银行"});
        consumetablebean.setDetials(new String[]{"8/8/2014","23/8/2014","25/8/2014","31/8/2014"});
        OtherTableIni.initConsumptionTable(0, hashMapForSchoolCard, consumetablebean);
        */
        //OtherTableIni.generateOtherList(this, (ListView) findViewById(R.id.consmuefull_list), consumetablebean.generateScholarismListOrOtherListData());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    private void showLoginFrame(final RelativeLayout LoginFrame) {
        consume_msg.setText("请输入校园卡密码");
        LoginFrame.postDelayed(new Runnable() {
            @Override
            public void run() {
                Animation fadeIn = AnimationUtils.loadAnimation(ConsumptionActivity.this, R.anim.fade_in);
                LoginFrame.setVisibility(View.VISIBLE);
                LoginFrame.startAnimation(fadeIn);
            }
        }, 500);
    }

    private void hideLoginFrame(final RelativeLayout LoginFrame) {
        LoginFrame.postDelayed(new Runnable() {
            @Override
            public void run() {
                Animation fadeIn = AnimationUtils.loadAnimation(ConsumptionActivity.this, R.anim.fade_out);
                LoginFrame.startAnimation(fadeIn);
                LoginFrame.setVisibility(View.GONE);
            }
        }, 250);
    }

    private void initWidget() {
        consume_login_frame = (RelativeLayout) findViewById(R.id.consume_login_frame);
        consume_password = (EditText) findViewById(R.id.consume_login_password);
        consume_button = (Button) findViewById(R.id.consume_button);
        consume_msg = (TextView) findViewById(R.id.consume_msg);
        consume_button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 执行输入校验
                if (validate()) {
                    loginPro();
                }
            }
        });
    }

    private boolean validate() {
        String pwd = consume_password.getText().toString().trim();
        if (pwd.equals("")) {
            Toast.makeText(this, "请输入校园卡密码", Toast.LENGTH_LONG);
            return false;
        }
        return true;
    }

    //用户登陆数据处理
    private void loginPro() {
        final String pwd = consume_password.getText().toString();
        new Thread() {
            @Override
            public void run() {
                Message msg = new Message();
                boolean verify = EcardModel.verify(pwd, self);
                if (verify) {
                    msg.what = 0x0200;
                } else {
                    msg.what = 0x0401;
                }
                handler.sendMessage(msg);
            }
        }.start();
        showReflashDialog("验证中...");
    }


    /**
     * 显示刷新的时候的等待进度条
     */
    private void showReflashDialog(String msg) {
        this.pd = new ProgressDialog(this);
        this.pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        this.pd.setCancelable(false);
        this.pd.setMessage(msg);
        this.pd.show();
    }

    /**
     * 结束刷新的时候的等待进度条
     */
    private void stopReflashDialog() {
        if (this.pd != null) {
            pd.dismiss();
        }
    }

    public void onDestory() {
        super.onDestroy();
        stopReflashDialog();
    }

}
